<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <a-form :form="form">
            <a-form-item style="display:none">
                <a-input v-decorator="['id']"/>
            </a-form-item>
            <a-row>
                <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                 :label="i18n('form.roleSelection','角色选择')">
                        <div class="inputBtnBox" style="width:40%;">
                            <span class="rx-groups">
                                      <a-input class="rx-inputs" v-model="roleName" :disabled="true"/>
                                      <span class="handClose" v-if="!pkId" @click="handRoleClose">
                                          <a-icon type="close"/>
                                      </span>
                            </span>
                            <a-button v-if="!pkId" class="btn choice" @click.stop="selectRole">
                                {{ $ti18('rxList.select', '选择') }}
                            </a-button>
                        </div>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <div class="data-set">
                        {{ i18n('form.dataConfiguration', '数据权限配置') }}
                    </div>
                    <a-collapse class="a-coll-box" v-model="activeKey" expand-icon-position="right"
                                @change="typeChange">
                        <a-collapse-panel :key="'type_'+dataType.idx" v-for="(dataType,index) in dataTypeList"
                                          forceRender>
                            <div class="select-box" slot="header" @mouseover="dataTypeOver(dataType)"
                                 @mouseleave="dataTypeLeave(dataType)">
                                <div class="s-type">
                                    <span class="s-type-title">
                                        {{ i18n('form.typeSelection', '类型选择') }}:
                                    </span>
                                    <div class="inputBtnBox">
                                        <span class="rx-groups">
                                                  <a-input class="rx-inputs" v-model="dataType.name" :disabled="true"/>
                                                  <span class="handClose" @click="handClose(dataType)">
                                                      <a-icon type="close"/>
                                                  </span>
                                        </span>
                                        <a-button class="btn choice" @click.stop="selectDataType(dataType)">
                                            {{ $ti18('rxList.select', '选择') }}
                                        </a-button>
                                    </div>
                                </div>
                                <div class="sqzk">
                                    <a-button class="a-btn" v-if="dataType.isBtnShow" type="primary" shape="circle"
                                              @click.stop="addType">
                                        <a-icon type="plus"/>
                                    </a-button>
                                    <a-button class="a-btn" v-if="dataType.isBtnShow" type="danger" shape="circle"
                                              @click.stop="removeType(index)">
                                        <a-icon type="delete"/>
                                    </a-button>
                                    <span>{{ activeKey == 'type_' + dataType.idx ? $ti18('rxList.putAwayBtn', '收起') : $ti18('rxList.openBtn', '展开') }}</span>
                                </div>
                            </div>
                            <div style="min-height: 250px;">
                                <div class="table-operator" v-if="dataType.columns.length>0">
                                    <a-button type="primary" @click="addRow(dataType)">
                                        {{ $ti18('rxList.add', '新增') }}
                                    </a-button>
                                    <a-button type="danger" @click="removeRow(dataType)">
                                        {{ $ti18('rxList.delBtn', '删除') }}
                                    </a-button>
                                </div>
                                <rx-tree-table :ref="'table_'+dataType.idx"
                                               v-if="dataType.columns.length>0"
                                               :dataSource="dataType.fields"
                                               :idField="dataType.idField"
                                               :columns="dataType.columns"
                                               :allowRowSelect="true"
                                               :multiSelect="true"
                                               :showPage="false"
                                               :resultAsTree="true"
                                               style="height: 200px;">
                        <span slot="sn" slot-scope="{text,record,index,blur}">
                            <a-input-number :min="1" v-model="record.sn" @blur="blur(index,'sn',text,record)"
                                            style="width:100%"/>
                        </span>
                                    <span slot="action" slot-scope="{text,index,record}" class="actionIcons">
                            <span @click.stop="onAddSibling(dataType,record)">
                                  {{i18n('form.addSibling','添加同级') }}
                              </span>
                            <span @click.stop="addChildDic(dataType,record)">
                                  {{i18n('form.addChild','添加子级') }}
                              </span>
                            <span @click.stop="removeRow(dataType,record)">
                                {{ $ti18('rxList.delBtn', '删除') }}
                            </span>
                            <template v-if="dataType.dataShowType!='FLAT' "></template>
                        </span>
                                </rx-tree-table>
                            </div>

                        </a-collapse-panel>
                    </a-collapse>
                </a-col>
            </a-row>
        </a-form>
    </rx-dialog>
</template>
<script>
import FormEntityDataSettingApi from '@/api/form/core/formEntityDataSetting'
import FormEntityDataTypeApi from "@/api/form/core/formEntityDataType";
import FormBoListApi from "@/api/form/core/formBoList";
import {BaseForm, RxDialog, RxGrid, Dialog, Util} from "@lowcode/jpaas-common-lib";
import DialogBox from "@/assets/js/DialogBox";

export default {
    name: 'FormEntityDataSettingEdit',
    mixins: [BaseForm],
    components: {
        RxDialog,
        RxGrid
    },
    data() {
        return {
            activeKey: [],
            dataTypeList: [],
            oriRoleId: "",
            roleId: "",
            roleName: ""
        }
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formEntityDataSetting", key);
        },
        onload_(values) {
            if (!values) {
                var idx = Util.randomId();
                this.activeKey = ['type_' + idx]
                this.dataTypeList = [{idx: idx, fields: [], columns: [], isBtnShow: false}];
            } else {
                this.oriRoleId = values.roleId;
                this.roleId = values.roleId;
                this.roleName = values.roleName;
                if (values.dataTypeId) {
                    var self = this;
                    var dataTypeIds = values.dataTypeId.split(",");
                    var dataTypeNames = values.dataTypeName.split(",");
                    for (var i = 0; i < dataTypeIds.length; i++) {
                        let dataType = {idx: Util.randomId(), fields: [], columns: [], isBtnShow: false};
                        if (i == 0) {
                            this.activeKey = ['type_' + dataType.idx];
                        }
                        dataType.id = dataTypeIds[i];
                        dataType.name = dataTypeNames[i];
                        FormEntityDataTypeApi.get(dataTypeIds[i]).then(res => {
                            var data = res.data;
                            dataType.idField = data.idField.toUpperCase();
                            dataType.textField = data.textField.toUpperCase();
                            dataType.dataShowType = data.dataShowType;
                            if (values.dataTypeDicMap && values.dataTypeDicMap[dataType.id]) {
                                var dicList = values.dataTypeDicMap[dataType.id];
                                for (var i = 0; i < dicList.length; i++) {
                                    var dic = dicList[i];
                                    var json = {};
                                    json[dataType.idField] = dic.idValue;
                                    json[dataType.textField] = dic.textValue;
                                    json['parentId'] = dic.parentValue;
                                    json['sn'] = dic.sn;
                                    dataType.fields.push(json);
                                }
                            }
                            dataType.dialogAlias = data.dialogAlias;
                            self.initColumns(dataType);
                        })
                        self.dataTypeList.push(dataType);
                    }
                }
            }
        },
        get(id) {
            var record = this.$parent.getSelectRecord();
            return FormEntityDataSettingApi.getByRoleId(record.roleId, record.appId);
        },
        parseDic(dicList, dataType, ary, parentId, path) {
            for (var j = 0; j < ary.length; j++) {
                var dic = {};
                var field = ary[j];
                var idValue = field[dataType.idField]
                dic['idValue'] = idValue;
                dic['textValue'] = field[dataType.textField];
                dic['parentValue'] = parentId;
                dic['path'] = path;
                dic['sn'] = field['sn'];
                if (field.children) {
                    this.parseDic(dicList, dataType, field.children, idValue, path + idValue + ".");
                }
                dicList.push(dic);
            }
        },
        validForm(values) {
            if (!this.roleId) {
                this.$message.error(this.i18n('form.configureRoles', '请配置角色！'));
                return false;
            }
            var ary = Util.deepClone(this.dataTypeList);
            for (var i = 0; i < this.dataTypeList.length; i++) {
                var dataType = this.dataTypeList[i];
                if (!dataType.id) {
                    ary.splice(i, 1);
                }
            }
            if (ary.length == 0) {
                this.$message.error(this.i18n('form.configureType', '请配置类型！'));
                return false;
            }
            return true;
        },
        save(values) {
            let appId = this.curApp.appId;
            if (appId) {
                values.appId = appId;
            }
            values.roleId = this.roleId;
            values.roleName = this.roleName;
            var dataTypeList = [];
            for (var i = 0; i < this.dataTypeList.length; i++) {
                var dataType = this.dataTypeList[i];
                if (!dataType.id) {
                    continue;
                }
                var dicList = [];
                var fields = this.$refs['table_' + dataType.idx][0].getData();
                this.parseDic(dicList, dataType, fields, '0', '0.');
                dataTypeList.push({dataTypeId: dataType.id, dataTypeName: dataType.name, dicList: dicList});
            }
            values.dataTypeList = JSON.stringify(dataTypeList);
            return FormEntityDataSettingApi.saveRole(values);
        },
        addData(dataType, callback) {
            if (!dataType.dialogAlias) {
                this.$message.error(this.i18n('form.configureDialog', '请配置对话框!'));
                return;
            }
            var self = this;
            DialogBox.dialog({key: dataType.dialogAlias}, {
                curVm: this
            }, function (action, data) {
                var fields = self.$refs['table_' + dataType.idx][0].getData();
                var ids = [];
                for (var i = 0; i < fields.length; i++) {
                    var field = fields[i];
                    ids.push(field[dataType.idField]);
                }
                var array = data.rows;
                if (!array) {
                    array = data;
                }
                for (var i = 0; i < array.length; i++) {
                    var row = array[i];
                    if (!ids.includes(row[dataType.idField])) {
                        delete row.children;
                        if (callback) {
                            callback(row);
                        }
                    }
                }
            });
        },
        addRow(dataType) {
            var table = this.$refs['table_' + dataType.idx][0];
            this.addData(dataType, function (row) {
                table.addNode({...row, sn: 1});
            })
        },
        addChildDic(dataType, record) {
            var table = this.$refs['table_' + dataType.idx][0];
            this.addData(dataType, function (row) {
                table.addNode({...row, sn: 1}, record);
            })
        },
        onAddSibling(dataType, record) {
            var table = this.$refs['table_' + dataType.idx][0];
            this.addData(dataType, function (row) {
                if (record.parentId && record.parentId != '0') {
                    var parentNode = table.getParentNode(record);
                    table.addNode({...row, sn: 1}, parentNode);
                    table.$forceUpdate();
                } else {
                    table.addNode({...row, sn: 1});
                }
            })
        },
        removeRow(dataType, record) {
            var table = this.$refs['table_' + dataType.idx][0];
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
                zIndex: 20000,
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    if (record) {
                        table.removeNode(record);
                    } else {
                        table.removeNodes();
                    }
                }
            })
        },
        dataTypeOver(dataType) {
            dataType.isBtnShow = true;
        },
        dataTypeLeave(dataType) {
            dataType.isBtnShow = false;
        },
        typeChange(key) {
            if (key.length == 0) {
                this.activeKey = [];
                return;
            }
            this.activeKey = [key[key.length - 1]];
        },
        addType() {
            this.dataTypeList.push({idx: Util.randomId(), fields: [], columns: [], isBtnShow: false});
        },
        removeType(index) {
            if (this.dataTypeList.length == 1) {
                this.$message.error(this.i18n('form.notAllowedDeleted', '最后一个不允许删除!'));
                return;
            }
            this.dataTypeList.splice(index, 1);
        },
        handClose(dataType) {
            delete dataType.id;
            delete dataType.name;
        },
        selectDataType(dataType) {
            var config = {curVm: this, widthHeight: ['800px', '600px'], data: {multiSelect: false}};
            var self = this;
            Dialog.openFormEntityDataTypeDialog(config, function (ary) {
                var data = ary[0];
                if (self.dataTypeList.filter(item => item.id == data.id).length > 0) {
                    self.$message.error(this.i18n('form.beSelected', '已选择此类型!'));
                    return;
                }
                dataType.id = data.id;
                dataType.name = data.name;
                dataType.idField = data.idField.toUpperCase();
                dataType.textField = data.textField.toUpperCase();
                dataType.dataShowType = data.dataShowType;
                dataType.dialogAlias = data.dialogAlias;
                self.initColumns(dataType);
            })
        },
        initColumns(dataType) {
            dataType.columns = [];
            FormBoListApi.getByKey(dataType.dialogAlias).then(res => {
                if (res.data.fieldsJson) {
                    var fields = JSON.parse(res.data.fieldsJson);
                    for (var i = 0; i < fields.length; i++) {
                        var field = fields[i];
                        var fieldName = field.field.toUpperCase();
                        if (fieldName == dataType.idField || fieldName == dataType.textField) {
                            dataType.columns.push({title: field.header, dataIndex: fieldName});
                        }
                    }
                    dataType.columns.push({
                        title: this.$ti18('rxList.index', '序号'),
                        dataIndex: 'sn',
                        width: 100,
                        allowCellEdit: true,
                        scopedSlots: {customRender: 'sn'}
                    });
                    dataType.columns.push({
                        title: this.$ti18('rxList.action', '操作'),
                        dataIndex: 'action',
                        scopedSlots: {customRender: 'action'}
                    });
                }
            })
        },
        handRoleClose() {
            this.roleId = "";
            this.roleName = "";
        },
        selectRole() {
            Dialog.openGroupDialog({
                curVm: this, data: {single: true, showDimId: false, dimId: '2'}, widthHeight: ['900px', '600px']
            }, function (self, data) {
                FormEntityDataSettingApi.validRole(data.groupId, self.curApp.appId).then(res => {
                    if (res.success || self.oriRoleId == data.groupId) {
                        self.roleId = data.groupId;
                        self.roleName = data.name;
                    } else {
                        self.$message.error(self.i18n('form.existsRole', '此角色已存在配置!'));
                    }
                })
            })
        }
    }
}
</script>
<style scoped>
.a-coll-box {
    margin: 0px 9px;
}

.sqzk {
    line-height: 36px;
}

.sqzk .a-btn {
    margin-right: 10px;
}

.s-type {
    display: flex;
}

.s-type-title {
    display: inline-block;
    margin-top: 8px;
    margin-right: 10px;
}

.select-box {
    display: flex;
    justify-content: space-between;
}

.data-set {
    border-left: 3px solid #1890fe;
    padding-left: 8px;
    margin-bottom: 10px;
    font-weight: 600;
    margin-left: 10px;
}

.choice {
    background-color: #f5f7fa;
    border-radius: 0px 5px 5px 0px;
    font-weight: normal !important
}

.rx-inputs {
    background-color: white;
}

.rxTagsBox {
    border-right: none;
}

.inputBtnBox {
    display: flex;
    vertical-align: middle;
    flex: 1;
    font-size: 0;
    text-align: left;
    margin-top: 4px;
}

.inputBtnBox .rx-groups {
    flex: 1;
    position: relative;
    width: 100%;
    min-height: 32px;
    line-height: normal;
}

.inputBtnBox .rx-groups .handClose {
    flex: none;
    display: none;
    position: absolute;
    right: 6px;
    text-align: center;
    width: 18px;
    height: 18px;
    line-height: 18px;
    top: 50%;
    margin-top: -9px;
    border-radius: 10px;
    text-align: center;
    background-color: #c0c5cc;
}

.inputBtnBox .btn {
    min-height: 32px !important;
    height: auto !important;
    border: 1px solid #d9d9d9;
    border-left: none;
}
.btn:focus{
    outline: none!important;
}
.inputBtnBox .rx-groups .handClose:hover {
    background-color: #1890ff;
}

.handClose i {
    font-size: 10px;
    color: #fff;
}

.inputBtnBox .rx-groups .rx-inputs {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    width: 100%;
    padding-right: 20px;
    color: #46494d;
}

.inputBtnBox .rx-groups:hover .rx-inputs {
    padding-right: 32px;
}

.inputBtnBox .rx-groups:hover .handClose {
    display: inline-block;
}

.inputBtnBox .rx-groups .handClose i {
    vertical-align: middle;
}

.inputBtnBox .rx-groups .handClose:before {
    content: '';
    display: inline-block;
    height: 100%;
    width: 0;
    vertical-align: middle;
}

.iconButton {
    font-size: 20px;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    margin-left: -1px;
}
</style>